package org.example.mock;

import com.github.javafaker.Faker;
import org.example.bean.StoreTraffic;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class StoreTrafficDataGenerator {
    private static final String DB_URL = "jdbc:mysql://hadoop102/bookstore?useSSL=false&requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;
    private static final Faker faker = new Faker(Locale.CHINA);

    public static void main(String[] args) {
        int days = 10; // 默认生成30天数据
        if (args.length >= 1) days = Integer.parseInt(args[0]);
        generateData(days);
    }

    public static void generateData(int days) {
        // 获取已有的店铺ID
        List<String> storeIds = fetchStoreIds();

        if (storeIds.isEmpty()) {
            System.err.println("错误：请先生成店铺数据");
            return;
        }

        List<StoreTraffic> trafficRecords = new ArrayList<>();
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days);

        for (String storeId : storeIds) {
            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                // 每天生成营业时间内的数据（9-21点）
                for (int hour = 9; hour <= 21; hour++) {
                    StoreTraffic record = StoreTraffic.builder()
                            .storeId(storeId)
                            .recordDate(date)
                            .hourOfDay(hour)
                            .customerCount(faker.number().numberBetween(20, 100))
                            .stayTimeAvg(BigDecimal.valueOf(faker.number().randomDouble(2, 15, 45)))
                            .conversionRate(BigDecimal.valueOf(faker.number().randomDouble(2, 10, 30)))
                            .createTime(LocalDateTime.now())
                            .build();
                    trafficRecords.add(record);
                }
            }
        }

        insertData(trafficRecords);
    }

    private static List<String> fetchStoreIds() {
        List<String> storeIds = new ArrayList<>();
        String sql = "SELECT store_id FROM store_info"; // 假设有店铺信息表store_info

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                storeIds.add(rs.getString("store_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return storeIds;
    }


    private static void insertData(List<StoreTraffic> trafficRecords) {
        String sql = "INSERT INTO store_traffic (store_id, record_date, hour_of_day, customer_count, " +
                "stay_time_avg, conversion_rate, create_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            conn.setAutoCommit(false);
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                for (int i = 0; i < trafficRecords.size(); i++) {
                    StoreTraffic record = trafficRecords.get(i);
                    pstmt.setString(1, record.getStoreId());
                    pstmt.setDate(2, Date.valueOf(record.getRecordDate()));
                    pstmt.setInt(3, record.getHourOfDay());
                    pstmt.setInt(4, record.getCustomerCount());
                    pstmt.setBigDecimal(5, record.getStayTimeAvg());
                    pstmt.setBigDecimal(6, record.getConversionRate());
                    pstmt.setTimestamp(7, Timestamp.valueOf(record.getCreateTime()));
                    pstmt.addBatch();

                    if ((i + 1) % BATCH_SIZE == 0) pstmt.executeBatch();
                }
                pstmt.executeBatch();
                conn.commit();
                System.out.println("成功插入" + trafficRecords.size() + "条客流量记录");
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}